from PyQt5.QtWidgets import  QMainWindow
from PyQt5.QtWidgets import QApplication , QMessageBox
from QTwin.login import Ui_mainWindow
from QTwin.U_answer import answer_Window
import socket
import sys
import threading
import json

from PyQt5 import QtCore

QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)


class NetClient(QMainWindow, Ui_mainWindow):
    def __init__(self):
        super(NetClient, self).__init__()
        super().__init__()
        self.ip = "192.168.88.131"
        self.port = 8787
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.setupUi(self)
        self.netConnect()
        self.pushButton.clicked.connect(self.loginserver)
        self.talk_count =0
        self.answer_count =0

    @QtCore.pyqtSlot()
    def loginserver(self):
        username = self.lineEdit.text()
        password = self.lineEdit_2.text()
        loginstr = json.dumps({"username": username, "password": password})
        print(loginstr)
        self.send(loginstr)
        data = self.recv()
        if data == "yes":
            self.talkwindow()
        else:
            QMessageBox.warning(None, '错误', "用户名密码错误", QMessageBox.Close)

    def netConnect(self):
        try:
            self.socket.connect((self.ip, self.port))
        except Exception as e:
            QMessageBox.warning(None, '错误', str(e), QMessageBox.Close)
            return
        th = threading.Thread(target=self.recv)
        th.setDaemon(True)
        th.start()

    def recv(self):
        while True:
            try:
                # 01010101
                data = self.socket.recv(4096).decode()  # 把二进制数解码成字符串类型，默认UTF-8
                return data
            except Exception as e:
                QMessageBox.warning(None, '错误', str(e), QMessageBox.Close)
                break

    def send(self, data):
        self.socket.send(data.encode())  # 编码 字符转字节类型

    def talkwindow(self):
        self.second_window = answer_Window()
        self.second_window.setupUi(self)
        self.tip2()
        threading.Thread(target=self.recv_msg).start()
        threading.Thread(target=self.rule_start).start()
        threading.Thread(target=self.game_start).start()
        self.work_thread()
    def check_input(self):
        self.user_input = self.second_window.textEdit.toPlainText()
        if self.talk_count < 6:
            if len(self.user_input) > 15:
                QMessageBox.information(self, '失败', '发送内容不可大于15个字！')
            else:
                QMessageBox.information(self, '成功', '发送成功！')
                self.talk_count += 1
                self.second_window.talk_num.setText(f'交流次数剩余：{5 - self.talk_count}')
                self.send_msg()
        else:
            QMessageBox.information(self, '失败', '交流次数已用完！')

    def answer_input(self):
        an_input = self.second_window.textEdit_2.toPlainText()
        if self.answer_count > 0:
            if an_input == self.word_data:
                QMessageBox.information(self, '成功', '答案正确！')
                self.socket.send("success".encode())
                self.result_sure("游戏成功！")
            else:
                QMessageBox.information(self, '失败', '答案错误！')
                self.answer_count -= 1
                self.second_window.answer_num.setText(f'提交次数剩余：{self.answer_count}')
        else:
            QMessageBox.information(self, '失败', '提交次数已用完！')
            self.socket.sendall("fail".encode())
            self.result_sure("游戏失败！")


    def btn_send(self):
        self.second_window.pushButton.clicked.connect(self.check_input)
    def answer_submit(self):
        self.second_window.pushButton_2.clicked.connect(self.answer_input)
    def recv_msg(self):
        while True:
            try:
                data = self.socket.recv(4096).decode()  # 把二进制数解码成字符串类型，默认UTF-8
                if data.startswith("1:"):
                    if data[2:] == "success":
                        print("success")
                    else:
                        print("error")
                elif data.startswith("2:"):
                    self.talk_count = 0
                    self.answer_count = 3
                    self.word_data = data[2:]
                    self.second_window.talk_num.setText(f'交流次数剩余：{5 - self.talk_count}')
                    self.second_window.answer_num.setText(f'提交次数剩余：{self.answer_count}')
                    print(self.word_data)
                else:
                    print(data)
                    data = data + "\n"
                    self.second_window.textBrowser.append(data)
            except Exception as e:
                QMessageBox.warning(None, '错误', str(e), QMessageBox.Close)
                break

    def receive_data(self):
        if (self.answer_count) == 0:
            data = "REQUEST_DATA"
            self.socket.send(data.encode())
            self.tip()
        else:
            self.tip3()
    @QtCore.pyqtSlot()
    def send_msg(self):
        msg = self.user_input          #self.second_window.textEdit.toPlainText()
        self.send(msg)
        self.second_window.textEdit.setPlainText("")

    def work_thread(self):
        threading.Thread(target=self.btn_send).start()
        threading.Thread(target=self.answer_submit).start()
    def rule_start(self):
        self.second_window.btn_rule.clicked.connect(self.rule)
    def rule(self):
        msgBox = QMessageBox()
        msgBox.setWindowTitle("游戏规则")
        msgBox.setText("""游戏分为描述端和回答端
                       描述端:
                       游戏开始你将会获得成语内容
                       你可以根据内容与描述端互相发送五次信息
                       发送后等待回答端提交答案并等待结果
                       注意发送内容不可包含题目中的任意信息且不可多余15个字
                       回答端:
                       游戏开始你将有五次与描述端的交流机会以及三次提交答案机会
                       提交答案与题目内容一致则游戏成功反则失败
                       """)
        msgBox.setStandardButtons(QMessageBox.Yes )
        reply = msgBox.exec_()
        if reply == QMessageBox.Yes:
            print("ok")
        else:
            self.close()
    def tip(self):
        msgBox = QMessageBox()
        msgBox.setWindowTitle("提示")
        msgBox.setText("游戏开始！")
        msgBox.setStandardButtons(QMessageBox.Yes )
        reply = msgBox.exec_()
        if reply == QMessageBox.Yes:
            print("ok")
        else:
            self.close()
    def result_sure(self,data):
        msgBox = QMessageBox()
        msgBox.setWindowTitle("确认")
        msgBox.setText(data)
        msgBox.setStandardButtons(QMessageBox.Yes )#| QMessageBox.No
        reply = msgBox.exec_()
        if reply == QMessageBox.Yes:
            print("ok")
        else:
            self.close()

    def game_start(self):
        self.second_window.pushButton_4.clicked.connect(self.receive_data)
    def tip2(self):
        msgBox = QMessageBox()
        msgBox.setWindowTitle("提示")
        msgBox.setText("请点击开始游戏！")
        msgBox.setStandardButtons(QMessageBox.Yes )
        reply = msgBox.exec_()
        if reply == QMessageBox.Yes:
            print("ok")
        else:
            self.close()

    def tip3(self):
        msgBox = QMessageBox()
        msgBox.setWindowTitle("提示")
        msgBox.setText("请先提交答案！")
        msgBox.setStandardButtons(QMessageBox.Yes )
        reply = msgBox.exec_()
        if reply == QMessageBox.Yes:
            print("ok")
        else:
            self.close()
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = NetClient()
    ex.show()
    sys.exit(app.exec_())